from django.shortcuts import render

# Create your views here.

from .models import *
from .ser import *
from rest_framework.views import APIView
from rest_framework.views import Response
from  django.core.paginator import Paginator

class JournalismM(APIView):
    def post(self,request):
        datas = JournalismSer(data=request.data)
        if datas.is_valid():
            datas.save()
            return Response({"code":200,"list":datas.data})
        else:
            print(datas.errors)
            return Response({"code":10010})

    def get(self, request):
        sr = Journalism.objects.all()
        p = Paginator(sr, 2)
        cpage = request.GET.get('p')
        rel = p.page(cpage)
        ser = JournalismSer(rel, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


import re
class Register(APIView):
    def post(self,request):
        # 用户名
        username = request.data.get('username')
        if not username:
            return Response({'code':10010})
        reg = re.match('\w{5,10}$',username)
        if not reg:
            return Response({'code':10011})
        user  = User.objects.filter(username=username).first()
        if user:
            return Response({'code':10012})
        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10013})
        mreg = re.match('^1[3-9]\d{9}$', mobile)
        if not mreg:
            return Response({'code': 10014})

class ClassifyM(APIView):
    def get(self,request):
        datas = Classify.objects.all()
        ser = ClassifySer(datas,many=True)
        return Response({"code":200,'list':ser.data})

class show_ClassifyM(APIView):
    def get(self,request):
        id = request.GET.get('id')
        datas = Classify.objects.filter(id=id).first()
        ser = Show_ClassifySer(datas)
        return Response({"code":200,'list':ser.data})



